<?php
namespace app\common\model;

use think\Model;
use think\Session;
use think\Db;

class LuntanArticle extends Model
{
    protected $insert = ['create_time'];

    /**
     * 文章作者
     * @param $value
     * @return mixed
     */
    protected function setAuthorAttr($value)
    {
        return $value ? $value : Session::get('admin_name');
    }

    /**
     * 反转义HTML实体标签
     * @param $value
     * @return string
     */
    protected function setContentAttr($value)
    {
        return htmlspecialchars_decode($value);
    }

    /**
     * 序列化photo图集
     * @param $value
     * @return string
     */
    protected function setPhotoAttr($value)
    {
        return serialize($value);
    }

    /**
     * 反序列化photo图集
     * @param $value
     * @return mixed
     */
    protected function getPhotoAttr($value)
    {
        return unserialize($value);
    }

    /**
     * 创建时间
     * @return bool|string
     */
    protected function setCreateTimeAttr()
    {
        return date('Y-m-d H:i:s');
    }

    /**
     * 获得文章列表数组(获得文章的发表人名称,所属栏目名称)
     * @return arr
     */
    public function getArticleList($cid,$keyword,$page)
    {
        //条件
        $map = [];
        if($cid){
            $map['cid'] = ['=',$cid];
        }
        if (!empty($keyword)) {
            $map['title'] = ['like', "%{$keyword}%"];
        }

        //查询
        $list = $this->where($map)->order(['create_time' => 'DESC'])->paginate(15, false, ['page' => $page]);
        //遍历
        $i = 0;
        for(;$i < count($list);$i++){
            if($list[$i]['is_user']){
                $list[$i]['username'] = Db('admin_user')->where('id',$list[$i]['uid'])->column('username');
            }else{
                $list[$i]['username'] = Db('user')->where('id',$list[$i]['uid'])->column('username');
            }
        }
        return $list;
    }

    /**
     * 获得点击文章的详情信息
     * @return arr
     */
    public function getArticle($id)
    {
        $listinfo = $this->find($id);
        if ($listinfo['is_user']) {
            $name = Db('admin_user')->where('id',$listinfo['uid'])->column('username');
        }else{
            $name = Db('user')->where('id',$listinfo['uid'])->column('username');
        }
        $listinfo['username'] = $name[0];
        return $listinfo;
    }

    /**
     * 获得点击文章的详情信息
     * @return arr
     */
    public function getReplyInfo($id,$page)
    {
        $replylist = Db('luntan_reply')->where('aid',$id)->order(['create_time' => 'asc'])->paginate(15, false, ['page' => $page]);
        
        $list = [];
        $i = 0;
        for(;$i<count($replylist);$i++){
            $afterlist[$i] = Db('luntan_after')->where('reply_id',$replylist[$i]['id'])->order('create_time','DESC')->select();
            $list[$i]['reply'] = $replylist[$i];
            $list[$i]['after'] = $afterlist[$i];
            $list[$i]['reply']['louceng'] = $i+1;
        }
        return $list;
    }


}